# -*- coding: utf-8 -*-
from . import BaseController
from backend.models import Video, VideoType, Tag, Element, VideoElement, SerieVideo
from backend.libs import myjson as json, play_info_util
from datetime import datetime


class ListController(BaseController):

    def get(self):
        vs = Video.objects

        product_name = self.get_argument('productName', '')
        vs = vs.filter(title__contains=product_name) if product_name else vs

        state = self.int_argument('state', 0)
        vs = vs.filter(state=state)

        vs = vs.order_by('show_order')
        
        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination(vs.all(), number_per_page=number_per_page, 
                                    m2m_fields=[], o2o_fields=[])
        return self.render_json(data=paginator)


class ListAllController(BaseController):

    def get(self):
        vs_list = Video.objects.filter(state=0).order_by('show_order').all()
        data = [ {'label': v.title, 'value': v.id } for v in vs_list ]
        return self.render_json(data={'videos': data})


class DetailController(BaseController):

    def get(self):
        id = self.int_argument('id', 0)
        if not id:
            return self.render_json(code=1001, msg='参数不能为空')
        v = Video.objects.filter(id=id).first()
        return self.render_json(data=v.to_detail_dict())


class UpdateController(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        return self.render_json()


class BatchUpdateVideoController(BaseController):

    def post(self):
        updated_videos = []
        data = json.loads(self.request.body)
        video_ids = data.get('videoIds', [])
        gs = Video.objects
        if not video_ids:
            return self.render_json(data={'videos': []})

        gs = gs.filter(id__in=video_ids)
        for attr in ('state', 'site'):
            if attr in data:
                gs.update(**{attr: data[attr], 'update_time': datetime.now()})

            for g in gs:
                g.save()

        updated_videos = gs.filter(id__in=video_ids)
        return self.render_json(data={'videos': [v.to_dict() for v in updated_videos]})


class CreateController(BaseController):
    
    def post(self):
        data = json.loads(self.request.body)
        title = data.get('title', '')
        if not title:
            return self.render_json(code=1001, msg='视频名称不能为空！视频创建失败！')
        vid = data.get('id', '')
        play_url = data.get('url', '')
        if not play_url:
            return self.render_json(code=1001, msg='必须上传视频！')

        if not vid:
            video = Video() 
            video.create_time =datetime.now()
        else:
            video = Video.objects.filter(id=vid).first()
            if not video:
                return self.render_json(code=1001, msg='视频不存在！')  
            VideoElement.objects.filter(video=video).delete()
            for t in video.tags.all():
                video.tags.remove(t)          

        video.title = title
        video.sub_title = data.get('sub_title', '')
        video.image_file = data['image_file']
        video.state = data['state']
        video.show_price = data.get('show_price', 1)
        kind = data.get('kind', 0)
        video.kind = kind
        video.url = play_url
        video.state = 0
        if play_url and play_url.rfind('.mp4') == -1 and play_url.rfind('.m3u8') == -1:
            play_info = play_info_util.get_play_info(play_url, kind)
            video.state = 1 # 只有获得播放地址才能上线
            if play_info:
                video.url = play_info['PlayURL']
                video.state = 0
        video.show_order = data['show_order']
        video.play_time = 0
        video.desc = data['desc']
        video.sub_desc = data['sub_desc']
    
        video.duration = data['duration']
        user_price = 0
        if data['user_price']:
            user_price = int(data['user_price']) * 100
        video.user_price = user_price
        extra_price = 0
        if data['extra_price']:
            extra_price = int(data['extra_price']) * 100
        video.extra_price = extra_price
        video.tips = data['tips']
        video.video_source = data.get('video_source', 1)
        video.detail = ','.join([ d for d in data['detail'] if d ])
        if data['ini_play_time']:
            video.ini_play_time = data['ini_play_time']
        if data['team_id']:
            video.team_id = data['team_id']
        if data['ini_sold_num']:
            video.ini_sold_num = data.get('ini_sold_num')
        if data['video_type_id']:
            video.video_type_id = data['video_type_id']
        if data['shoot_day']:
            video.shoot_day = data['shoot_day']
        video.price_unit = data['price_unit']
        video.content = data['content']
        video.save()

        if len(data['elements']) > 0:
            elements_dict = {}
            for ele_data in data['elements']:
                if not ele_data['elementId']:
                    continue
                elements_dict[ele_data['elementId']] = ele_data['num']
            elements = Element.objects.filter(id__in=list(elements_dict.keys())).all()
            for e in elements:
                ve = VideoElement()
                ve.video = video
                ve.element = e
                ve.num = elements_dict[e.id]
                ve.save()

        # 建立视频与标签的关系
        if len(data['tags']) > 0:
            tag_ids = [ t.get('tagId') for t in data['tags'] if t.get('tagId', '') ]
            tag_list = Tag.objects.filter(id__in=tag_ids).all()
            for t in tag_list:
                video.tags.add(t)
                video.save()

        data = {}
        return self.render_json(msg='视频创建成功！', data=data)


class DeleteController(BaseController):
    
    def post(self):
        data = json.loads(self.request.body)
        video_id = data['id']
        if not video_id:
            return self.render_json_code_999(msg='参数不能为空')
        v = Video.objects.filter(id=video_id).first()
        if not v:
            return self.render_json_code_999(msg='视频不存在')
        VideoElement.objects.filter(video=v).delete()
        SerieVideo.objects.filter(video=v).delete()
        v.delete()

        data = {'vid': video_id}
        return self.render_json(msg='视频删除成功！', data=data)
     

class BatchDeleteController(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        video_ids = data.get('videoIds', [])
        if not video_ids:
            return self.render_json_code_999(msg='视频参数不能为空')
        Video.objects.filter(id__in=video_ids).delete()

        return self.render_json(msg='删除成功')


class VideoTypeController(BaseController):

    def get(self):
        video_type_list = [ vt.to_detail_dict() for vt in VideoType.objects.order_by('show_order').all() ]

        data = {
            'videoTypes': video_type_list
        }
        return self.render_json(data=data)


class VideoTimeListController(BaseController):

    def get(self):
        video_time_list = [ vt.to_dict() for vt in VideoTime.objects.order_by('show_order').all()]
        data = {
            'videoTimes': video_time_list
        }
        return self.render_json(data=data)        

class ListVideoOrderStateController(BaseController):

    def get(self):
        vos_list = VideoOrderState.objects.all()
        return self.render_json(data={'stateOptions':[vos.to_option_dict() for vos in vos_list if vos.id not in [10, 11, 14, 15, 99] ]})
